package com.imist.cake.service;

import com.imist.cake.common.MybatisUtils;
import com.imist.cake.entity.Cake;
import com.imist.cake.mapper.CakeMapper;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;

public class CakeService {
    public List<Cake> getCakeByCategoryId(Long categoryId,Integer page ,Integer size){
        SqlSession sqlSession = MybatisUtils.openSession();
        CakeMapper mapper = sqlSession.getMapper(CakeMapper.class);
        try{
            return mapper.getCakeByCategoryId(categoryId,(page - 1)*size,size);
        }finally {
            sqlSession.close();
        }
    }

    /**
     * 新增蛋糕
     * @param cake
     */
    public void addCake(Cake cake){
        Date now = new Date();
        cake.setCreateTime(now);
        cake.setUpdateTime(now);
        SqlSession sqlSession = MybatisUtils.openSession();
        try {
            CakeMapper cakeMapper = sqlSession.getMapper(CakeMapper.class);
            cakeMapper.addCake(cake);
            sqlSession.commit();
        }finally {
            sqlSession.close();
        }
    }

    /**
     * 统计给定分类ID下的蛋糕数量
     * @param categoryId 分类ID
     * @return 统计结果
     */
    public int countCakeByCategoryId(Long categoryId){
        SqlSession sqlSession = MybatisUtils.openSession();
        try{
            CakeMapper cakeMapper = sqlSession.getMapper(CakeMapper.class);
            return cakeMapper.countCakeByCategoryId(categoryId);
        }finally {
            sqlSession.close();
        }
    }

    /**
     * 根据ID查询只包含图片信息的蛋糕实体；
     * @param id
     * @return
     */
    public Cake getCakeImg(Long id) {
        SqlSession sqlSession = MybatisUtils.openSession();
        try{
            CakeMapper cakeMapper = sqlSession.getMapper(CakeMapper.class);
            return cakeMapper.getImg(id);
        }finally {
            sqlSession.close();
        }

    }
}
